package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {


    @Value("${file.url}")
    private String fileUrl;

    //上传图片  file_id
    // 文件入参名称 必须叫 file   页面提交文件的时候 文件的Key值就是file
    @RequestMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws Exception{
        //全路径
        String url = ClassUtils.getDefaultClassLoader().
                getResource("tracker.conf").getPath();

        //初始化 Tracker客户端的IP地址
        ClientGlobal.init(url);

        // 192.168.200.128:22122  连接Tracker服务器
        TrackerClient trackerClient = new TrackerClient();
        //stoager 的IP Post
        TrackerServer trackerServer = trackerClient.getConnection();

        //创建Storage的客户端  目地是为了连接Storage服务器
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);

        //工具类
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());

        //上传图片
        String path = storageClient1.upload_file1
                (file.getBytes(),ext
                        , null);


        System.out.println(fileUrl + path);
        // http://192.168.200.128:8080/group1/M00/00/00/wKjIgF5NF0eAIt60AAT8_AoEzOU968.jpg
        return Result.ok(fileUrl + path);

    }
}
